package com.mall.controller;

import com.mall.config.tts.SpeechSynthesizerDemo;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;

@Controller
public class VoiceController {
    private Log logger = LogFactory.getLog(VoiceController.class);

    @RequestMapping(value = "/genVoice")
    public ResponseEntity<String> genVoice(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String voice = ServletRequestUtils.getStringParameter(request, "voice", "Eva");
        String text = ServletRequestUtils.getStringParameter(request, "text", null);
        // 指定文件路径
        File file = SpeechSynthesizerDemo.getFile(voice, text);

        // 检查文件是否存在
        if (!file.exists()) {
            logger.info("文件不存在，准备生成新的问题：" + voice + " - " + text);
            SpeechSynthesizerDemo demo = new SpeechSynthesizerDemo();
            demo.process(voice, text);
            demo.shutdown();
        }

        // 读取文件内容
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] data = IOUtils.toByteArray(fileInputStream);
        fileInputStream.close();

        String base64Content = Base64.getEncoder().encodeToString(data);

        // 将数据前添加 data:audio/mp3;base64,
        String dataUrl = "data:audio/mp3;base64," + base64Content;

        // 返回给客户端
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-Disposition", "attachment; filename=" + file.getName())
                .body(dataUrl);
    }

}
